import { ProForm } from "@/components/ProForm";
import type { Dayjs } from "dayjs";
import dayjs from "dayjs";
import { data } from "./data";
import { DownloadOutlined, PlusOutlined} from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button, DatePicker,
  Form,
  Input,
  InputNumber,
  message, Modal,
  Row,
  Space,
  Table,
  Pagination,
  type TableProps
} from "antd";
import type { FC, Key } from "react";
import { useState,useEffect } from "react";
import { http } from "@/utils/request";

type TableDataType = {
  projectCode: string;
  projectName: string;
  projectDescription: string;
  createdBy: string;
  applicableDept: string;
  createdTime: string | Dayjs;
  scoreDownLimit: number;
  scoreUpperLimit: number;
}

type TableRowSelection<T> = TableProps<T>["rowSelection"];

const { confirm } = Modal;
const AddOrSubtractPoints = () => {
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [list, setList] = useState([]);
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});
  const [editingRowKeys, setEditingRowKeys] = useState<Key[]>([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const [id,setId] = useState(null);

  const columns = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text: string, _record: TableDataType, index: number) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "项目编码",
      dataIndex: "projectCode"
    },
    {
      align: "center",
      title: "项目名称",
      dataIndex: "projectName"
    },
    {
      align: "center",
      title: "项目描述",
      dataIndex: "projectDescription"
    },
    {
      align: "center",
      title: "创建人",
      dataIndex: "createdBy"
    },
    {
      align: "center",
      title: "适用部门",
      dataIndex: "applicableDept"
    },
    {
      align: "center",
      title: "创建时间",
      dataIndex: "createdTime"
    },
    {
      align: "center",
      title: "加（减）分数下限",
      dataIndex: "scoreDownLimit"
    },
    {
      align: "center",
      title: "加（减）分数上限",
      dataIndex: "scoreUpperLimit"
    },
    {
      title: "操作",
			width:250,
			align:'center',
      fixed: 'right',
      render: (_, record) => {
        return (
          <>
            <Button type={'link'} onClick={()=>{
              edit(record)
            }}>编辑</Button>
            <Button type={'link'} danger onClick={()=>{
              confirm({
                title: '提示?',
                content: '此操作将永久删除该数据，是否继续?',
                onOk() {
                  delData(record.id)
                },
              });
            }}>删除</Button>
          </>
        )
      }
    }
  ]
  const delData = async(id:number|string)=>{
    const res = await http.get({
      url:'/PmPlusMinusScoreDictionary/remove',
      params:{
        dictionaryId:id,
      }
    })
    if(res.code==200){
      message.success('删除成功!');
      getList();
    }else{
      message.error(res.msg);
    }
  }
  const create = () => {
    setCurrentEdit({});
    setOpen(true);
    setId(null);
    // 延迟执行确保弹窗已打开
    setTimeout(() => {
      editForm.resetFields();
      editForm.setFieldValue('createdBy', '张三');
    }, 100);
  }

  const edit = (formData:TableDataType) => {
    setOpen(true);
    const data = JSON.parse(JSON.stringify(formData));
    data.createdTime = dayjs(data.createdTime, 'YYYY-MM-DD')
    setId(data.id);
    editForm.setFieldsValue(data)
    setCurrentEdit(data);
  }

  const handleOk = async() => {
    const values = await editForm.validateFields();
    values.createdTime = dayjs(values.createdTime).format('YYYY-MM-DD');
    // 校验成功，执行保存操作并关闭Modal
    if(JSON.stringify(currentEdit) === "{}"){
      addSave(values);
    }else{
      editSave(values);
    }
  }
  //新增接口
  const addSave = async(formData:object) =>{
    const res = await http.post({
      url:'/PmPlusMinusScoreDictionary/add',
      data:formData,
    })
    if(res.code==200){
      setOpen(false);
      message.success('项目新增成功!');
      getList();
    }else{
      message.error(res.msg);
    }
  }
  //编辑接口
  const editSave = async(formData:object) =>{
    const res = await http.post({
      url:'/PmPlusMinusScoreDictionary/update',
      data:{id,...formData}
    })
    if(res.code==200){
      setOpen(false);
      message.success('项目修改成功!');
      getList();
    }else{
      message.error(res.msg);
    }
  }
  const handleCancel = () => {
    editForm.resetFields();
    setOpen(false);
  }
  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }

  //查询接口
  const getList = async() =>{
    try {
      const createdTime = form.getFieldValue('createdTime')//创建时间
      const res = await http.get({
        url:'/PmPlusMinusScoreDictionary/qryList',
        params:{
          applicableDept:form.getFieldValue('applicableDept'),
          createdTime:createdTime?dayjs(createdTime).format('YYYY-MM-DD'):'',
          createdBy:form.getFieldValue('createdBy'),
          pageNum:pageNum,
          pageSize:pageSize,
        }
      })
      setList(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  useEffect(()=>{
    getList();
  },[pageNum,pageSize])
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'} onSearch={getList} onReset={getList}>
        <Form.Item
          label={'适用部门'}
          name="applicableDept"
        >
          <Input placeholder="请输入适用部门" />
        </Form.Item>
        <Form.Item
          label={'创建时间'}
          name="createdTime"
        >
          <DatePicker />
        </Form.Item>
        <Form.Item
          label={'创建人'}
          name="createdBy"
        >
          <Input placeholder="请输入创建人" />
        </Form.Item>
      </ProForm>

      <Row className={'mb-[20px]'} justify={'end'}>
        <Space>
          <Button type={'link'} icon={<DownloadOutlined />}>下载模板</Button>
          <Button type={'link'} icon={<DownloadOutlined />}>导入</Button>
          <Button type={'primary'} icon={<PlusOutlined />} onClick={create}>新增</Button>
        </Space>
      </Row>

      <Table
        className={"mb-[20px]"}
        dataSource={list}
        columns={columns}
        rowKey={(record) => `${record.id}`}
        pagination={false}
      ></Table>
      <Pagination
        className={'m-[20px] text-end'}
        current={pageNum}
        pageSize={pageSize}
        total={total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={changePagination}
      />

      <Modal
        open={open}
        title={`${JSON.stringify(currentEdit) === "{}" ? "新增" : "编辑"}考核计算公式配置`}
        afterClose={() => editForm.resetFields()}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={'提交'}
        cancelText={'取消'}
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form form={editForm} initialValues={currentEdit} labelCol={{span: 6}} autoComplete="off">
          <Form.Item
            label={'项目编码'}
            name={'projectCode'} rules={[{ required: true, message: '请填写项目编码!' }]}
          >
            <Input placeholder={"请输入项目编码"}></Input>
          </Form.Item>
          <Form.Item
            label={'项目名称'}
            name={'projectName'} rules={[{ required: true, message: '请填写项目名称!' }]}
          >
            <Input placeholder={"请输入项目名称"}></Input>
          </Form.Item>
          <Form.Item
            label={'项目描述'}
            name={'projectDescription'} rules={[{ required: true, message: '请填写项目描述!' }]}
          >
            <Input placeholder={"请输入项目描述"}></Input>
          </Form.Item>
          <Form.Item
            label={'创建人'}
            name={'createdBy'} rules={[{ required: true, message: '请填写创建人!' }]}
          >
            <Input placeholder={"请输入创建人"} disabled></Input>
          </Form.Item>
          <Form.Item
            label={'适用部门'}
            name={'applicableDept'} rules={[{ required: true, message: '请填写适用部门!' }]}
          >
            <Input placeholder={"请输入适用部门"}></Input>
          </Form.Item>
          <Form.Item
            label={'创建时间'}
            name={'createdTime'} rules={[{ required: true, message: '请选择创建时间!' }]}
          >
            <DatePicker className={"w-full"} />
          </Form.Item>
          <Form.Item
            label={'加(减)分数下限'}
            name={'scoreDownLimit'} rules={[{ required: true, message: '请填写加(减)分数下限!' }]}
          >
            <InputNumber className={'w-full'} min={0} placeholder={"请输入"}></InputNumber>
          </Form.Item>
          <Form.Item
            label={'加(减)分数上限'}
            name={'scoreUpperLimit'} rules={[{ required: true, message: '请填写加(减)分数上限!' }]}
          >
            <InputNumber className={'w-full'} min={0} placeholder={"请输入"}></InputNumber>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  )
}

export default AddOrSubtractPoints;
